<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.io.output.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />
<title>Scholar Aide</title>
</head>
<body>
	<jsp:include page="/includes/header.jsp" />
	<div id="wrapper">
		<div id="content">
			<%
				// Text Input Variables. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
				String name = "";
				String sponsors = "";
				String reward = "";
				String num_recipients = "";
				String major = "";
				String min_gpa = "";
				String min_standing = "";
				String max_standing = "";
				String deadline = "";
				String description = "";
				boolean finished = false;

				// Store the location to write the file and the submitted file. /////////////////////////////////////////////////////////////////////
				File file = null;
				FileItem input = null;

				int maxFileSize = 5000 * 1024;
				int maxMemSize = 5000 * 1024;
				ServletContext context = pageContext.getServletContext();
				String filePath = application.getRealPath("scholarship_documents") + "\\";

				// Verify the content type
				String contentType = request.getContentType();
				if ((contentType.indexOf("multipart/form-data") >= 0)) {

					DiskFileItemFactory factory = new DiskFileItemFactory();
					// maximum size that will be stored in memory
					factory.setSizeThreshold(maxMemSize);
					// Location to save data that is larger than maxMemSize.
					factory.setRepository(new File(filePath));

					// Create a new file upload handler
					ServletFileUpload upload = new ServletFileUpload(factory);
					// maximum file size to be uploaded.
					upload.setSizeMax(maxFileSize);
					try {
						// Parse the request to get file items.
						@SuppressWarnings("unchecked")
						List<FileItem> fileItems = upload.parseRequest(request);

						// Process the uploaded file items
						Iterator<FileItem> i = fileItems.iterator();

						while (i.hasNext()) {
							FileItem fi = (FileItem) i.next();
							if (!fi.isFormField()) {
								// Get the uploaded file parameters
								String fieldName = fi.getFieldName();
								String fileName = fi.getName();
								boolean isInMemory = fi.isInMemory();
								long sizeInBytes = fi.getSize();
								// Write the file
								if (fileName.lastIndexOf("\\") >= 0) {
									file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
								} else {
									file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
								}
								//fi.write(file);
								input = fi; // Store the submitted file. Do not write until the text components have been validated.
							} else {
								// FileItem is a form field.
								String value = fi.getString();
								if (fi.getFieldName().equalsIgnoreCase("name")) {
									name = value;
								} else if (fi.getFieldName().equalsIgnoreCase("sponsors")) {
									sponsors = value;
								} else if (fi.getFieldName().equalsIgnoreCase("reward")) {
									reward = value;
								} else if (fi.getFieldName().equalsIgnoreCase("num_recipients")) {
									num_recipients = value;
								} else if (fi.getFieldName().equalsIgnoreCase("major")) {
									major = value;
								} else if (fi.getFieldName().equalsIgnoreCase("min_gpa")) {
									min_gpa = value;
								} else if (fi.getFieldName().equalsIgnoreCase("min_standing")) {
									min_standing = value;
								} else if (fi.getFieldName().equalsIgnoreCase("max_standing")) {
									max_standing = value;
								} else if (fi.getFieldName().equalsIgnoreCase("deadline")) {
									deadline = value;
								} else if (fi.getFieldName().equalsIgnoreCase("description")) {
									description = value;
								} else if (fi.getFieldName().equalsIgnoreCase("finished")) {
									finished = Boolean.parseBoolean(value);
								}
							}
						}
						out.println("</body>");
						out.println("</html>");
					} catch (Exception ex) {
						out.println(ex);
						ex.printStackTrace();
					}
				}

				// Input validation. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
				boolean name_test = true;
				boolean sponsors_test = true;
				boolean reward_test = true; // Check if the reward is a double greater than 0.
				try {
					reward_test = Double.parseDouble(reward) > 0;
				} catch (Exception e) {
					reward_test = false;
				}
				boolean num_recipients_test = true; // Check if the number of recipients is an integer greater than 0.
				try {
					num_recipients_test = Integer.parseInt(num_recipients) > 0;
				} catch (Exception e) {
					num_recipients_test = false;
				}
				boolean major_test = true;
				boolean min_gpa_test = true; // Check if the GPA is a double from 0.0 - 4.0.
				try {
					double gpa = Double.parseDouble(min_gpa);
					min_gpa_test = gpa >= 0 && gpa <= 4.0;
				} catch (Exception e) {
					min_gpa_test = false;
				}
				boolean min_standing_test = true; // Check if the minimum year is an integer from 1 - 4.
				try {
					int year = Integer.parseInt(min_standing);
					min_standing_test = year > 0 && year < 5;
				} catch (Exception e) {
					min_standing_test = false;
				}
				boolean max_standing_test = true; // Check if the maximum year is an integer from 1 - 4.
				try {
					int year = Integer.parseInt(max_standing);
					max_standing_test = year > 0 && year < 5;
				} catch (Exception e) {
					max_standing_test = false;
				}
				boolean deadline_test = true; // Check if the deadline is a date.
				try {
					java.sql.Date.valueOf(deadline);
				} catch (Exception e) {
					deadline_test = false;
				}
				boolean description_test = true;

				// Compile error messages. //////////////////////////////////////////////////////////////////////////////////////////////////////////
				String errors = "";
				if (!reward_test) {
					errors += "* Reward money should be a number greater than 0.<br />";
				}
				if (!num_recipients_test) {
					errors += "* The number of recipients should be a number greater than 0.<br />";
				}
				if (!min_gpa_test) {
					errors += "* The minimum GPA should be a number from 0.0 to 4.0.<br/>";
				}
				if (!min_standing_test) {
					errors += "* The minimum standing should be a number from 1-4 inclusive.<br />";
				}
				if (!max_standing_test) {
					errors += "* The maximum standing should be a number from 1-4 inclusive.<br />";
				}
				if (!deadline_test) {
					errors += "* Deadline must be in the yyyy-mm-dd format.<br />";
				}

				// If there are errors return to the new scholarship page. //////////////////////////////////////////////////////////////////////////
				if (!errors.equals("") && finished) {
					session.setAttribute("errors", errors);
					session.setAttribute("name", name);
					session.setAttribute("sponsors", sponsors);
					session.setAttribute("reward", reward);
					session.setAttribute("num_recipients", num_recipients);
					session.setAttribute("major", major);
					session.setAttribute("min_gpa", min_gpa);
					session.setAttribute("min_standing", min_standing);
					session.setAttribute("max_standing", max_standing);
					session.setAttribute("deadline", deadline);
					session.setAttribute("description", description);
					session.setAttribute("file", "new_scholarship.jsp");
					response.sendRedirect("dashboard.jsp");
				} else {
					// Getting information and updating the database.
					java.sql.Connection conn = null;
					try {
						String myJDBCDriver = (String) session.getAttribute("myJDBCDriver");
						String myURL = (String) session.getAttribute("myURL");
						String myUserID = (String) session.getAttribute("myUserID");
						String myPassword = (String) session.getAttribute("myPassword");

						// Connect to the database.
						Class.forName(myJDBCDriver).newInstance();
						java.util.Properties sysprops = System.getProperties();
						sysprops.put("user", myUserID);
						sysprops.put("password", myPassword);
						conn = java.sql.DriverManager.getConnection(myURL, sysprops);

						java.sql.Statement statement = conn.createStatement();
						name = "'" + name + "'";
						sponsors = "'" + sponsors + "'";
						reward = "'" + reward + "'";
						num_recipients = "'" + num_recipients + "'";
						major = "'" + major + "'";
						min_gpa = "'" + min_gpa + "'";
						min_standing = "'" + min_standing + "'";
						max_standing = "'" + max_standing + "'";
						deadline = "'" + deadline + "'";
						description = "'" + description + "'";
						int finish_int = 0;
						if (finished) {
							finish_int = 1;
						}
						//finished = "'" + finished + "'";
						//user = "'" + session.getAttribute("user") + "'";
						String query = "INSERT INTO scholarships (name,sponsors,reward,num_recipients,major,min_gpa,min_standing,max_standing,deadline,description,finished,submitter) ";
						query += "VALUES (" + name + "," + sponsors + "," + reward + "," + num_recipients + "," + major + "," + min_gpa + ","
								+ min_standing + "," + max_standing + "," + deadline + "," + description + ",'" + finish_int + "','"
								+ session.getAttribute("user") + "'" + ")";
						statement.executeUpdate(query);

						// Save the uploaded file.
						java.sql.ResultSet rs = statement.executeQuery("SELECT LAST_INSERT_ID()");
						rs.next();
						try {
							String extension = file.getName().substring(file.getName().lastIndexOf('.'), file.getName().length());
							file = new File(file.getParent() + "\\" + rs.getString(1) + extension);
							input.write(file);
						} catch (Exception e) { // No file was uploaded.
						}

						session.setAttribute("errors", "Scholarship Added!");
						session.setAttribute("file", "new_scholarship.jsp");
						response.sendRedirect("dashboard.jsp");
					} catch (Exception e) {
						e.printStackTrace();
						out.print(e.toString());
					} finally {
						try {
							conn.close();
						} catch (Exception ee) {
						}
					}
				}
			%>
		</div>
	</div>
	<jsp:include page="/includes/footer.jsp" />
</body>
</html>